package com.recharge.service.impl;

import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.recharge.common.util.*;
import com.recharge.core.entity.*;
import com.recharge.core.mapper.GoodsMerchantMapper;
import com.recharge.core.mapper.MerchantCallbakMapper;
import com.recharge.domain.query.OrderStatusQueryDO;
import com.recharge.domain.vo.*;
import com.recharge.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.ResultSupport;
import com.recharge.core.mapper.ProviderOrderMapper;
import com.recharge.domain.query.ProviderOrderQueryDO;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author reagan
 * @since 2020-08-19
 */
@Service
public class ProviderOrderServiceImpl extends ServiceImpl<ProviderOrderMapper, ProviderOrderEntity> implements ProviderOrderService {


	@Autowired
    private OrderService orderService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ProviderService providerService;
    @Autowired
    private ProviderApiService providerApiService;
    @Autowired
    private MerchantCallbakMapper merchantCallbakMapper;
    @Autowired
    private TransactionService transactionService;
    @Autowired
    private RefundService refundService;
    @Autowired
    private GoodsMerchantMapper goodsMerchantMapper;
    @Autowired
    private ProviderOrderMapper providerOrderMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Value("${node.name}")
    private Integer nodeName;

    @Autowired
    private RedisTemplate<String, Object> redisMessageTemplate;
	
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    
    public ResultDO add(ProviderOrderDO domain) {
        logger.info("写供应单" + domain);
        ProviderOrderEntity entity = new ProviderOrderEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.info("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        entity.setProviderDate(Calendar.getInstance().getTime());
        entity.setNodeName(nodeName);
		boolean res = false;
        try {
            res = this.save(entity);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ORDER_ADD_PROVIDER);
            logger.info("error code：" + ErrorCode.ORDER_ADD_PROVIDER.getCode() + " msg" + ErrorCode.ORDER_ADD_PROVIDER.getMsg());
            return result;
        }

        domain = getDomain(entity);
        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);
        return result;
    }

    public ResultDO updateProviderOrderStatus(String orderId, String providerOrderNo, int status, String voucherNo, String serialNumber) {
        logger.info("updateProviderOrderStatus 更新供应单:" + orderId + ":" + providerOrderNo + ":" + status + ":" + voucherNo + ":" + serialNumber);
        ResultDO result = new ResultSupport();

        ProviderOrderEntity entity = null;
        try {
            entity = this.baseMapper.selectOne(Wrappers.<ProviderOrderEntity>lambdaQuery().eq(ProviderOrderEntity::getOrderId, orderId)
                    .eq(ProviderOrderEntity::getSerialNumber, serialNumber));
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        entity.setProviderOrderNo(providerOrderNo);
        entity.setIsManual(Constant.PROVIDER_AUTO);
        entity.setIsOver(Constant.PROVIDER_ORDER_IS_OVER_1);
        entity.setStatus(status);
        entity.setNodeName(nodeName);
        entity.setProcessTime(System.currentTimeMillis() - entity.getProviderDate().getTime());
        if(entity.getProviderMethod().intValue() == Constant.PROVIDER_METHOD_2) {
            entity.setVoucherNo(voucherNo);
        }
        int res = -1;
        try {
            res = this.baseMapper.deleteById(entity.getId());
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        if(res >= 0) {
            try {
                res = this.baseMapper.insert(entity);
            } catch (Exception e) {
                e.printStackTrace();
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                return result;
            }
        }

        result.setModel(ResultDO.FIRST_MODEL_KEY, getDomain(entity));
        return result;

    }

    public ResultDO get(String id) {

        ResultDO result = new ResultSupport();
        ProviderOrderEntity entity = null;

        try {
            entity = this.getById(id);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        ProviderOrderDO domain = getDomain(entity);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }

    public ResultDO get(String providerId, String providerOrderNo) {

        ResultDO result = new ResultSupport();
        ProviderOrderEntity entity = null;

        try {
            entity = this.getOne(Wrappers.<ProviderOrderEntity>lambdaQuery().eq(ProviderOrderEntity::getProviderId, providerId).eq(ProviderOrderEntity:: getProviderOrderNo, providerOrderNo));
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        ProviderOrderDO domain = getDomain(entity);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }
    
    public ResultDO remove(String id, String userName) {
        ResultDO result = new ResultSupport();

        boolean res = false;

        ProviderOrderEntity entity = new ProviderOrderEntity();
        entity.setId(id);
        entity.setIsDelete(Constant.IS_DELETE);
        try {
            res = this.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ORDER_DELETE_PROVIDER);
            logger.info("error code：" + ErrorCode.ORDER_DELETE_PROVIDER.getCode() + " msg" + ErrorCode.ORDER_DELETE_PROVIDER.getMsg());
            return result;
        }

        return result;
    }

    public ResultDO getProviderOrderFail(String orderNo, String providerId) {
        logger.info("order:" + orderNo +" providerId:" + providerId);
        ResultDO result = new ResultSupport();
        int count = 0;
        try {
            count = this.baseMapper.selectCount(Wrappers.<ProviderOrderEntity>lambdaQuery()
                    .eq(ProviderOrderEntity::getStatus, Constant.PROVIDER_ORDER_STATUS_fail)
                    .eq(ProviderOrderEntity::getOrderNo, orderNo)
                    .eq(ProviderOrderEntity::getProviderId, providerId)
                    .eq(ProviderOrderEntity::getIsDelete, Constant.IS_DELETE_FALSE));
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ORDER_GET_PROVIDER);
            logger.info("error code：" + ErrorCode.ORDER_GET_PROVIDER.getCode() + " msg" + ErrorCode.ORDER_GET_PROVIDER.getMsg());
            return result;
        }
        logger.info("getProviderOrderFail result:" + count +" providerId:" + providerId);
        if(count == 0) {
            result.setSuccess(true);
        } else {
            result.setSuccess(false);
        }
        return result;
    }

    @Override
    public ResultDO findList(ProviderOrderQueryDO query) {
        ProviderOrderEntity entity = new ProviderOrderEntity();
        String[] queryData = query.getOrderDate();
        Double[] queryProcessTime = query.getProcessTime();
        query.setProcessTime(null);
        query.setOrderDate(null);
        ResultDO result = BeanUtilsExtends.copy(entity, query);
        if (!result.isSuccess()) {
            logger.info("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        QueryWrapper<ProviderOrderEntity> wrapper = new QueryWrapper<ProviderOrderEntity>(entity);

        if(queryData != null && queryData.length == 2){
            wrapper.lambda().between(ProviderOrderEntity::getOrderDate, queryData[0], queryData[1]);
        }
        if(queryProcessTime != null && queryProcessTime.length == 2){
            if(queryProcessTime[0] != null && queryProcessTime[1] != null){
                wrapper.lambda().between(ProviderOrderEntity::getProcessTime, queryProcessTime[0] * 1000, queryProcessTime[1] * 1000);
            }
        }

        if(query.getServiceProvider() != null){
            wrapper.lambda().like(ProviderOrderEntity::getServiceProvider, query.getServiceProvider());
        }
        if(query.getProviderIds() != null && query.getProviderIds().length >0){
            if(query.isQueryProviderType()){
                Stream.of(query.getProviderIds()).forEach(providerId -> {
                    wrapper.lambda().ne(ProviderOrderEntity::getProviderId, providerId);
                });
            } else {
                wrapper.lambda().and( newWrapper -> {
                    newWrapper.and( providerIdWrapper -> {
                        Stream.of(query.getProviderIds()).forEach(providerId -> {
                            providerIdWrapper.or(itemWrapper -> itemWrapper.eq(ProviderOrderEntity::getProviderId, providerId));
                        });
                    });
                });
            }
        }
        if(query.getMerchantIds() != null && query.getMerchantIds().length >0){
            if(query.isQueryMerchantType()){
                Stream.of(query.getMerchantIds()).forEach(merchantId -> {
                    wrapper.lambda().ne(ProviderOrderEntity::getMerchantId, merchantId);
                });
            } else {
                wrapper.lambda().and( newWrapper -> {
                    newWrapper.and( merchantIdWrapper -> {
                        Stream.of(query.getMerchantIds()).forEach(merchantId -> {
                            merchantIdWrapper.or(itemWrapper -> itemWrapper.eq(ProviderOrderEntity::getMerchantId, merchantId));
                        });
                    });
                });
            }
        }
        if(StringUtils.isNotEmpty(query.getGoodsName())){
            entity.setGoodsName(null);
            wrapper.lambda().like(ProviderOrderEntity::getGoodsName, query.getGoodsName());
        }
        if(query.getStatus() != null && query.getStatus() == Constant.PROVIDER_ORDER_STATUS_3){
            wrapper.lambda().orderByDesc(ProviderOrderEntity::getProcessTime, ProviderOrderEntity::getOrderDate);
        } else {
            wrapper.lambda().orderByDesc(ProviderOrderEntity::getOrderDate);
        }
        List<ProviderOrderEntity> list = null;
        try {
            list = baseMapper.selectList(wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<ProviderOrderDO> doList = getDomainList(list);

        result.setModel(ResultDO.FIRST_MODEL_KEY, doList);
        return result;
    }
    
    public ResultDO find(ProviderOrderQueryDO query) {
    	ProviderOrderEntity entity = new ProviderOrderEntity();
        String[] queryData = query.getOrderDate();
        Double[] queryProcessTime = query.getProcessTime();
        query.setProcessTime(null);
        query.setOrderDate(null);
        ResultDO result = BeanUtilsExtends.copy(entity, query);
        if (!result.isSuccess()) {
            logger.info("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        QueryWrapper<ProviderOrderEntity> wrapper = new QueryWrapper<ProviderOrderEntity>(entity);
        Page<ProviderOrderEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());

        if(queryData != null && queryData.length == 2){
            wrapper.lambda().between(ProviderOrderEntity::getOrderDate, queryData[0], queryData[1]);
        }
        if(queryProcessTime != null && queryProcessTime.length == 2){
            if(queryProcessTime[0] != null && queryProcessTime[1] != null){
                wrapper.lambda().between(ProviderOrderEntity::getProcessTime, queryProcessTime[0] * 1000, queryProcessTime[1] * 1000);
            }
        }

        if(query.getServiceProvider() != null){
            wrapper.lambda().like(ProviderOrderEntity::getServiceProvider, query.getServiceProvider());
        }
        if(query.getProviderIds() != null && query.getProviderIds().length >0){
            if(query.isQueryProviderType()){
                Stream.of(query.getProviderIds()).forEach(providerId -> {
                    wrapper.lambda().ne(ProviderOrderEntity::getProviderId, providerId);
                });
            } else {
                wrapper.lambda().and( newWrapper -> {
                    newWrapper.and( providerIdWrapper -> {
                        Stream.of(query.getProviderIds()).forEach(providerId -> {
                            providerIdWrapper.or(itemWrapper -> itemWrapper.eq(ProviderOrderEntity::getProviderId, providerId));
                        });
                    });
                });
            }
        }
        if(query.getMerchantIds() != null && query.getMerchantIds().length >0){
            if(query.isQueryMerchantType()){
                Stream.of(query.getMerchantIds()).forEach(merchantId -> {
                    wrapper.lambda().ne(ProviderOrderEntity::getMerchantId, merchantId);
                });
            } else {
                wrapper.lambda().and( newWrapper -> {
                    newWrapper.and( merchantIdWrapper -> {
                        Stream.of(query.getMerchantIds()).forEach(merchantId -> {
                            merchantIdWrapper.or(itemWrapper -> itemWrapper.eq(ProviderOrderEntity::getMerchantId, merchantId));
                        });
                    });
                });
            }
        }
        if(StringUtils.isNotEmpty(query.getGoodsName())){
            entity.setGoodsName(null);
            wrapper.lambda().like(ProviderOrderEntity::getGoodsName, query.getGoodsName());
        }
        if(query.getStatus() != null && query.getStatus() == Constant.PROVIDER_ORDER_STATUS_3){
            wrapper.lambda().orderByDesc(ProviderOrderEntity::getProcessTime, ProviderOrderEntity::getOrderDate);
        } else {
            wrapper.lambda().orderByDesc(ProviderOrderEntity::getOrderDate);
        }
        IPage<ProviderOrderEntity> iPage = null;

        try {
            iPage = baseMapper.selectPage(page, wrapper);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        
        List<ProviderOrderDO> doList = getDomainList(iPage.getRecords());

//        if( doList != null && doList.size() > 0){
//            doList.stream().forEach( item -> {
//                ResultDO selectResult = providerService.get(item.getProviderId());
//                if(!selectResult.isSuccess()){
//                    logger.info("error code：" + selectResult.getErrorCode().getCode() + " msg" + selectResult.getErrorCode().getMsg());
//                } else {
//                    ProviderDO domain = (ProviderDO) selectResult.getModel(ResultDO.FIRST_MODEL_KEY);
//                    if(domain != null){
//                        item.setProviderName(domain.getProviderName());
//                    }
//                }
//                selectResult = merchantService.get(item.getMerchantId());
//                if(!selectResult.isSuccess()){
//                    logger.info("error code：" + selectResult.getErrorCode().getCode() + " msg" + selectResult.getErrorCode().getMsg());
//                } else {
//                    MerchantDO domain = (MerchantDO) selectResult.getModel(ResultDO.FIRST_MODEL_KEY);
//                    if(domain != null){
//                        item.setMerchantName(domain.getMerchantName());
//                    }
//                }
//            });
//        }

        PageDO<ProviderOrderDO> pageDO = new PageDO<>();

        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(doList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
        return result;
    }

    public ResultDO reportOrder(ProviderOrderQueryDO query) {
        ProviderOrderEntity entity = new ProviderOrderEntity();
        String[] queryData = query.getOrderDate();
        Double[] queryProcessTime = query.getProcessTime();
        query.setProcessTime(null);
        query.setOrderDate(null);
        ResultDO result = BeanUtilsExtends.copy(entity, query);
        if (!result.isSuccess()) {
            logger.info("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        QueryWrapper<ProviderOrderEntity> wrapper = new QueryWrapper<ProviderOrderEntity>(entity);
        Page<ProviderOrderEntity> page = new Page<>(query.getCurrentPage(),query.getPageSize());

        if(queryData != null && queryData.length == 2){
            wrapper.lambda().between(ProviderOrderEntity::getOrderDate, queryData[0], queryData[1]);
        }
        if(queryProcessTime != null && queryProcessTime.length == 2){
            if(queryProcessTime[0] != null && queryProcessTime[1] != null){
                wrapper.lambda().between(ProviderOrderEntity::getProcessTime, queryProcessTime[0] * 1000, queryProcessTime[1] * 1000);
            }
        }

        if(query.getServiceProvider() != null){
            wrapper.lambda().like(ProviderOrderEntity::getServiceProvider, query.getServiceProvider());
        }

        if(query.getProviderIds() != null && query.getProviderIds().length >0){
            if(query.isQueryProviderType()){
                Stream.of(query.getProviderIds()).forEach(providerId -> {
                    wrapper.lambda().ne(ProviderOrderEntity::getProviderId, providerId);
                });
            } else {
                wrapper.lambda().and( newWrapper -> {
                    newWrapper.and( providerIdWrapper -> {
                        Stream.of(query.getProviderIds()).forEach(providerId -> {
                            providerIdWrapper.or(itemWrapper -> itemWrapper.eq(ProviderOrderEntity::getProviderId, providerId));
                        });
                    });
                });
            }
        }
        if(query.getMerchantIds() != null && query.getMerchantIds().length >0){
            if(query.isQueryMerchantType()){
                Stream.of(query.getMerchantIds()).forEach(merchantId -> {
                    wrapper.lambda().ne(ProviderOrderEntity::getMerchantId, merchantId);
                });
            } else {
                wrapper.lambda().and( newWrapper -> {
                    newWrapper.and( merchantIdWrapper -> {
                        Stream.of(query.getMerchantIds()).forEach(merchantId -> {
                            merchantIdWrapper.or(itemWrapper -> itemWrapper.eq(ProviderOrderEntity::getMerchantId, merchantId));
                        });
                    });
                });
            }
        }
        if(StringUtils.isNotEmpty(query.getGoodsName())){
            entity.setGoodsName(null);
            wrapper.lambda().like(ProviderOrderEntity::getGoodsName, query.getGoodsName());
        }


        wrapper.select("sum(case when status = 3 then 1 else 0 end) as processNumber",
                "sum(case when status = 2 then 1 else 0 end) as successNumber",
                "sum(case when status = -1 then 1 else 0 end) as failNumber",
                "sum(case when status = 4 then 1 else 0 end) as unconfirmedNumber",
                "count(1) as totalNumber",
                "sum(case when status = 2 then (amount*(cast(agent_discount*10000 as SIGNED)))/10000 else 0 end) as sale",
                "sum(case when status = 2 then (amount*(cast(cost_discount*10000 as SIGNED)))/10000 else 0 end) as cost"
        );
        IPage<ProviderOrderEntity> iPage = null;
        List<ProviderOrderEntity> list = null;
        try {
            list = providerOrderMapper.selectList(wrapper);
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }



        List<ProviderOrderDO> doList = getDomainList(list);
        if(doList!=null&&doList.size()>0){
            ProviderOrderDO orderdo = doList.get(0);
            orderdo.setProcessNumber(orderdo.getProcessNumber()==null?0:orderdo.getProcessNumber());
            orderdo.setSuccessNumber(orderdo.getSuccessNumber()==null?0:orderdo.getSuccessNumber());
            orderdo.setFailNumber(orderdo.getFailNumber()==null?0:orderdo.getFailNumber());
            orderdo.setUnconfirmedNumber(orderdo.getUnconfirmedNumber()==null?0:orderdo.getUnconfirmedNumber());
            orderdo.setSale(orderdo.getSale()==null?0.0:orderdo.getSale());
            orderdo.setCost(orderdo.getCost()==null?0.0:orderdo.getCost());
            doList.add(orderdo);
        }

        PageDO<ProviderOrderDO> pageDO = new PageDO<>();


        pageDO.setData(doList);

        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);
        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    private boolean updateBatchProviderOrder(List<ProviderOrderEntity> list){
        Boolean flog = false;
        try {
            flog = this.updateBatchById(list);
        } catch (Exception e) {
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return flog;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
	public ResultDO updateBatch(String resetType, Integer status, String[] ids, Integer isOver, Map<String, String> map, String userName) {
		ResultDO result = new ResultSupport();

        List<ProviderOrderEntity> list = null;
        try {
            list = baseMapper.selectBatchIds(Stream.of(ids).collect(Collectors.toList()));
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        if(list != null && list.size() >0){
            try {
                for(ProviderOrderEntity item : list){
                    item.setOperator(userName);
                    item.setIsOver(isOver);
                    item.setIsManual(Constant.MANUAL_PROVIDER_ORDER_STATUS_1);
                    item.setIsRemedy(Constant.IS_REMEDY);
                    if(Constant.PROVIDER_ORDER_STATUS_2 == status) {
                        item.setStatus(status);
                        if(map != null && !map.isEmpty()){
                            item.setVoucherNo(String.valueOf(map.get(item.getOrderId())));
                            item.setRemark(String.valueOf(map.get(item.getOrderId() + "remark")));
                        } else {
                            item.setRemark("人工操作(成功)");
                        }
                        updateProviderOrderSuccess(item);
                    } else {
                        if(map != null && !map.isEmpty()){
                            item.setRemark(String.valueOf(map.get(item.getOrderId() + "remark")));
                        } else {
                            item.setRemark("人工操作(失败)");
                        }
                        item.setStatus(status);
                        updateProviderOrderFail(item, resetType);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
		return result;
	}

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    private void updateProviderOrderSuccess(ProviderOrderEntity item){
        ResultDO result = new ResultSupport();
        //修改供应商为成功
        boolean flog = false;
        flog = this.update(item, Wrappers.<ProviderOrderEntity>lambdaQuery()
                .eq(ProviderOrderEntity::getId, item.getId())
                .eq(ProviderOrderEntity::getStatus, Constant.PROVIDER_ORDER_STATUS_3)
                .or()
                .eq(ProviderOrderEntity::getId, item.getId())
                .eq(ProviderOrderEntity::getStatus, Constant.PROVIDER_ORDER_STATUS_4));
        if(!flog) return;//修改失败返回
        //修改订单状态
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setStatus(Constant.RECHARGE_ORDER_STATUS_3);
        orderEntity.setVoucherNo(item.getVoucherNo());
        flog = orderService.update(orderEntity,  Wrappers.<OrderEntity>lambdaQuery()
                .eq(OrderEntity::getId, item.getOrderId())
                .eq(OrderEntity::getStatus, Constant.RECHARGE_ORDER_STATUS_5)
                .or()
                .eq(OrderEntity::getId, item.getId())
                .eq(OrderEntity::getStatus, Constant.RECHARGE_ORDER_STATUS_7));
        if(flog){
            //从库中获取订单信息
            result = orderService.get(item.getOrderId());
            if(!result.isSuccess()){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return;
            }
            OrderDO orderDO = (OrderDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
            if(orderDO == null){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return;
            }
            //回调下游
            result = merchantService.get(item.getMerchantId());
            if(!result.isSuccess()){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return;
            }
            MerchantDO domain = (MerchantDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
            ResultDO resultDomain = merchantService.callback(orderDO.getMerchantSerialNumber(), item.getOrderNo(), item.getRechargeNumber(), item.getVoucherNo(),  0, "", domain.getCallback());
            if(!resultDomain.isSuccess()){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return;
            }
        }
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    private void updateProviderOrderFail(ProviderOrderEntity item, String resetType){
        try {
            ResultDO result = new ResultSupport();
            boolean flog = false;
            flog = this.update(item, Wrappers.<ProviderOrderEntity>lambdaQuery()
                    .eq(ProviderOrderEntity::getId, item.getId())
                    .eq(ProviderOrderEntity::getStatus, Constant.PROVIDER_ORDER_STATUS_3)
                    .or()
                    .eq(ProviderOrderEntity::getId, item.getId())
                    .eq(ProviderOrderEntity::getStatus, Constant.PROVIDER_ORDER_STATUS_4));
            if(!flog) return;//修改失败返回
            //退款
            result = orderService.get(item.getOrderId());
            if(!result.isSuccess()){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return;
            }
            OrderDO orderDO = (OrderDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
            if(orderDO == null){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return;
            }
            if(Constant.PROVIDER_ORDER_STATUS_fail == item.getStatus() && item.getIsOver() == Constant.PROVIDER_ORDER_IS_OVER_0){
                RechargeDO domain = new RechargeDO();
                domain.setMerchantNo(orderDO.getMerchantNo());
                domain.setMerchantId(orderDO.getMerchantId());
                domain.setMerchantName(orderDO.getMerchantName());
                domain.setGoodsNo(orderDO.getGoodsNo());
                domain.setRechargeNumber(orderDO.getRechargeNumber());
                domain.setPrice(orderDO.getAmount().longValue());
                domain.setCallbackUrl(orderDO.getCallback());
                domain.setSerialNumber(orderDO.getMerchantSerialNumber());
                domain.setOrderNo(orderDO.getOrderNo());
                domain.setGoodsQuantity(orderDO.getGoodsQuantity());
                domain.setProviderId(orderDO.getProviderId());
                domain.setOrderId(orderDO.getId());
                //重置到下一个
                if(Constant.RESET_TYPE_NEXT.equals(resetType)){
                    domain.setRetryStatus(Constant.ORDER_RETRY_STATUS_3);
                }
                //重置到当前上游
                if(Constant.RESET_TYPE_CURRENT.equals(resetType)){
                    domain.setRetryStatus(Constant.ORDER_RETRY_STATUS_2);
                }
                //重置所有上游
                if(Constant.RESET_TYPE_ALL.equals(resetType)){
                    domain.setRetryStatus(Constant.ORDER_RETRY_STATUS_1);
                }
                logger.info("重试供货单：" + domain);
                redisMessageTemplate.convertAndSend("order:" + nodeName,  domain);
                return;
            }
            //供应结束
            if(Constant.PROVIDER_ORDER_STATUS_fail == item.getStatus() && item.getIsOver() == Constant.PROVIDER_ORDER_IS_OVER_1) {
                try {
                    //退款
                    RefundDO refundDomain = new RefundDO();
                    refundDomain.setMerchantNo(orderDO.getMerchantNo());
                    refundDomain.setMerchantId(orderDO.getMerchantId());
                    refundDomain.setGoodsTitle(orderDO.getTitle());
                    refundDomain.setMerchantName(orderDO.getMerchantName());
                    refundDomain.setAmount(Double.valueOf(String.valueOf(ArithUtils.mul(Double.parseDouble(String.valueOf(orderDO.getAmount())), Double.parseDouble(String.valueOf(orderDO.getAgentDiscount()))))).longValue());
                    refundDomain.setType(Constant.REFUND_TYPE_MANUAL);
                    ResultDO resultDomain = refundService.submit(refundDomain);
                    if(resultDomain.isSuccess()){
                        refundDomain = (RefundDO) resultDomain.getModel(ResultDO.FIRST_MODEL_KEY);
                        orderDO.setRefundNo(refundDomain.getRefundNo());
                    } else {
                        logger.debug("申请退款失败,订单号：" + orderDO.getOrderNo() + "error code：" + resultDomain.getErrorCode().getCode() + " msg" + resultDomain.getErrorCode().getMsg());
                        orderDO.setProviderCallbackInfo("退款失败,请核实");
                    }
                } catch (Exception e) {
                    logger.debug("退款失败，订单号：" + orderDO.getOrderNo());
                    orderDO.setProviderCallbackInfo("退款失败,请核实");
                }
                //修改订单
                OrderEntity orderEntity = new OrderEntity();
                orderEntity.setStatus(Constant.RECHARGE_ORDER_STATUS_4);
                orderEntity.setRefundNo(orderDO.getRefundNo());
                orderEntity.setProviderCallbackInfo(orderDO.getProviderCallbackInfo());
                flog = orderService.update(orderEntity,  Wrappers.<OrderEntity>lambdaQuery()
                        .eq(OrderEntity::getId, item.getOrderId())
                        .eq(OrderEntity::getStatus, Constant.RECHARGE_ORDER_STATUS_5)
                        .or()
                        .eq(OrderEntity::getId, item.getId())
                        .eq(OrderEntity::getStatus, Constant.RECHARGE_ORDER_STATUS_7));
                if(flog){
                    //回调下游
                    result = merchantService.get(item.getMerchantId());
                    if(!result.isSuccess()){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return;
                    }
                    MerchantDO domain = (MerchantDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
                    ResultDO resultDomain = merchantService.callback(orderDO.getMerchantSerialNumber(), item.getOrderNo(), item.getRechargeNumber(), item.getVoucherNo(),  ErrorCode.API_ORDER_PROVIDER_FAIL.getCode(), "", domain.getCallback());
                    if(!resultDomain.isSuccess()){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    /**
     * 批量核单
     * @param ids
     * @return
     */
    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO vouchingBatch(String[] ids, String userName) {
        ResultDO result = new ResultSupport();

        List<String> orderIdsList = Stream.of(ids).collect(Collectors.toList());

        //查询供货单列表
        List<ProviderOrderEntity> providerOrderList = null;
        if(orderIdsList != null && !orderIdsList.isEmpty()){
            try {
                providerOrderList = baseMapper.selectBatchIds(orderIdsList);
            } catch (Exception e) {
                result.setSuccess(false);
                result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                return result;
            }
        }

        if(providerOrderList != null && providerOrderList.size() >0){
            List<ProviderOrderEntity> successProviderOrderList = new ArrayList<>();
            List<ProviderOrderEntity> failProviderOrderList = new ArrayList<>();
            List<ProviderOrderEntity> nuknowProviderOrderList = new ArrayList<>();
            List<ProviderOrderEntity> errorProviderOrderList = new ArrayList<>();

            for (ProviderOrderEntity item : providerOrderList){
                ResultDO resultDomain = providerApiService.getByProviderNo(item.getProviderNo());
                if(resultDomain.isSuccess()){
                    ProviderApiDO obj = (ProviderApiDO) resultDomain.getModel(ResultDO.FIRST_MODEL_KEY);
                    OrderStatusQueryDO domain = new OrderStatusQueryDO();
                    domain.setSerialNo(item.getSerialNumber());
                    domain.setInterfaceNum(obj.getInterfaceNum());
                    domain.setOrderFindUrl(obj.getOrderFindUrl());
                    domain.setPrivateKey(obj.getPrivateKey());
                    domain.setUserId(obj.getUserId());
                    resultDomain = providerApiService.queryOrder(domain);
                    if(resultDomain.isSuccess()){
                       Integer providerStatus = resultDomain.getModel(ResultDO.FIRST_MODEL_KEY) == null ? null : (Integer) resultDomain.getModel(ResultDO.FIRST_MODEL_KEY);
                       String voucherNo = resultDomain.getModel(ResultDO.SECOND_MODEL_KEY) == null ? "" : (String) resultDomain.getModel(ResultDO.SECOND_MODEL_KEY);
                       if(providerStatus != null && providerStatus.intValue() == Constant.CALL_BACK_SUCCESS){
                           ProviderOrderEntity providerOrderEntity = new ProviderOrderEntity();
                           providerOrderEntity.setStatus(Constant.PROVIDER_ORDER_STATUS_2);
                           providerOrderEntity.setId(item.getId());
                           providerOrderEntity.setOrderId(item.getOrderId());
                           providerOrderEntity.setVoucherNo(voucherNo);
                           providerOrderEntity.setRemark("主动核实(成功)");
                           successProviderOrderList.add(providerOrderEntity);
                       } else if(providerStatus != null && providerStatus.intValue() == Constant.CALL_BACK_FAIL){
                           ProviderOrderEntity providerOrderEntity = new ProviderOrderEntity();
                           providerOrderEntity.setStatus(Constant.PROVIDER_ORDER_STATUS_fail);
                           providerOrderEntity.setOrderId(item.getOrderId());
                           providerOrderEntity.setId(item.getId());
                           providerOrderEntity.setRemark("主动核实(失败):" + (String) resultDomain.getModel(ResultDO.THIRD_MODEL_KEY));
                           failProviderOrderList.add(providerOrderEntity);
                       } else {
                           if(resultDomain.getModel(ResultDO.THIRD_MODEL_KEY) != null){
                               ProviderOrderEntity providerOrderEntity = new ProviderOrderEntity();
                               providerOrderEntity.setId(item.getId());
                               providerOrderEntity.setRemark((String) resultDomain.getModel(ResultDO.THIRD_MODEL_KEY));
                               errorProviderOrderList.add(providerOrderEntity);
                           }
                       }
//                       else if(providerStatus != null && providerStatus.intValue() == Constant.CALL_BACK_NUKNOW.intValue()){
//                           ProviderOrderEntity providerOrderEntity = new ProviderOrderEntity();
//                           providerOrderEntity.setStatus(Constant.PROVIDER_ORDER_STATUS_4);
//                           providerOrderEntity.setOperator(userName);
//                           providerOrderEntity.setId(item.getId());
//                           nuknowProviderOrderList.add(providerOrderEntity);
//                       }
//                       else if(providerStatus != null && providerStatus.intValue() == Constant.CALL_BACK_PROCESS.intValue()){
//                           ProviderOrderEntity providerOrderEntity = new ProviderOrderEntity();
//                           providerOrderEntity.setStatus(Constant.PROVIDER_ORDER_STATUS_3);
//                           providerOrderEntity.setOperator(userName);
//                           providerOrderEntity.setId(item.getId());
//                           nuknowProviderOrderList.add(providerOrderEntity);
//                       }
                    } else {
                        ProviderOrderEntity providerOrderEntity = new ProviderOrderEntity();
                        providerOrderEntity.setId(item.getId());
                        providerOrderEntity.setRemark((String) resultDomain.getModel(ResultDO.THIRD_MODEL_KEY));
                        errorProviderOrderList.add(providerOrderEntity);
                    }
                } else {
                    ProviderOrderEntity providerOrderEntity = new ProviderOrderEntity();
                    providerOrderEntity.setId(item.getId());
                    providerOrderEntity.setRemark("未查询到接口API");
                    errorProviderOrderList.add(providerOrderEntity);
                }
            };
            if(successProviderOrderList != null && successProviderOrderList.size() >0){
                Map<String, String> map = new HashMap<>();
                String[] array = successProviderOrderList.stream().map( item -> {
                    map.put(item.getOrderId(), item.getVoucherNo());
                    map.put(item.getOrderId() + "remark", item.getRemark());
                    return item.getId();
                }).toArray(String[]::new);
               result = this.updateBatch("", Constant.PROVIDER_ORDER_STATUS_2, array, Constant.PROVIDER_ORDER_IS_OVER_1, map, userName);
               if(!result.isSuccess()){
                   result.setSuccess(false);
                   result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                   logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                   TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                   return result;
               }
            }
            if(failProviderOrderList != null && failProviderOrderList.size() >0){
                Map<String, String> map = new HashMap<>();
                String[] array = failProviderOrderList.stream().map( item -> {
                    map.put(item.getOrderId() + "remark", item.getRemark());
                    return item.getId();
                }).toArray(String[]::new);
                result = this.updateBatch("", Constant.PROVIDER_ORDER_STATUS_fail, array, Constant.PROVIDER_ORDER_IS_OVER_1, map, userName);
                if(!result.isSuccess()){
                    result.setSuccess(false);
                    result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                    logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return result;
                }
            }
            if(nuknowProviderOrderList != null && nuknowProviderOrderList.size() >0){
                try {
                    this.updateBatchById(nuknowProviderOrderList);
                } catch (Exception e) {
                    result.setSuccess(false);
                    result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                    logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return result;
                }
            }
            if(errorProviderOrderList != null && errorProviderOrderList.size() >0){
                try {
                    this.updateBatchById(errorProviderOrderList);
                } catch (Exception e) {
                    result.setSuccess(false);
                    result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
                    logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return result;
                }
            }
        }
        return result;
    }

    @Override
    public ResultDO vouchingProviderOrder(ProviderOrderDO param) {
        ResultDO result = new ResultSupport();
        if(StringUtils.isEmpty(param.getId())){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PARAM_GET_ERROR);
            logger.info("error code：" + ErrorCode.PARAM_GET_ERROR.getCode() + " msg" + ErrorCode.PARAM_GET_ERROR.getMsg());
            return result;
        }
        result = this.get(param.getId());
        if(!result.isSuccess()){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ORDER_GET_PROVIDER);
            logger.info("error code：" + ErrorCode.ORDER_GET_PROVIDER.getCode() + " msg" + ErrorCode.ORDER_GET_PROVIDER.getMsg());
            return result;
        }

        ProviderOrderDO domain = (ProviderOrderDO) result.getModel(ResultDO.FIRST_MODEL_KEY);
        ResultDO resultDomain = providerApiService.getByProviderNo(domain.getProviderNo());
        if(resultDomain.isSuccess()) {
            ProviderApiDO obj = (ProviderApiDO) resultDomain.getModel(ResultDO.FIRST_MODEL_KEY);
            OrderStatusQueryDO queryDomain = new OrderStatusQueryDO();
            queryDomain.setSerialNo(domain.getSerialNumber());
            queryDomain.setInterfaceNum(obj.getInterfaceNum());
            queryDomain.setOrderFindUrl(obj.getOrderFindUrl());
            queryDomain.setPrivateKey(obj.getPrivateKey());
            queryDomain.setUserId(obj.getUserId());
            resultDomain = providerApiService.queryOrder(queryDomain);
            if(resultDomain.isSuccess()){
                Integer providerStatus = resultDomain.getModel(ResultDO.FIRST_MODEL_KEY) == null ? null : (Integer) resultDomain.getModel(ResultDO.FIRST_MODEL_KEY);
                String voucherNo = resultDomain.getModel(ResultDO.SECOND_MODEL_KEY) == null ? "" : (String) resultDomain.getModel(ResultDO.SECOND_MODEL_KEY);
                if(providerStatus != null && providerStatus.intValue() == Constant.CALL_BACK_SUCCESS){//成功
                    domain.setVoucherNo(voucherNo);
                    domain.setStatus(Constant.PROVIDER_ORDER_STATUS_2);
                } else if(providerStatus != null && providerStatus.intValue() == Constant.CALL_BACK_FAIL){//失败
                    domain.setStatus(Constant.PROVIDER_ORDER_STATUS_fail);
                    domain.setRemark((String) resultDomain.getModel(ResultDO.THIRD_MODEL_KEY));
                } else if(providerStatus != null && providerStatus.intValue() == Constant.CALL_BACK_PROCESS){//充值中
                    if(resultDomain.getModel(ResultDO.THIRD_MODEL_KEY) != null){
                        domain.setStatus(Constant.PROVIDER_ORDER_STATUS_3);
                        domain.setRemark((String) resultDomain.getModel(ResultDO.THIRD_MODEL_KEY));
                    }
                } else if(providerStatus != null && providerStatus.intValue() == Constant.CALL_BACK_NUKNOW){//未确认
                    if(resultDomain.getModel(ResultDO.THIRD_MODEL_KEY) != null){
                        domain.setStatus(Constant.PROVIDER_ORDER_STATUS_4);
                        domain.setRemark((String) resultDomain.getModel(ResultDO.THIRD_MODEL_KEY));
                    }
                } else if(providerStatus != null && providerStatus.intValue() == Constant.CALL_BACK_NOT_EXIST){//订单不存在
                    int time = (int)resultDomain.getModel(ResultDO.FOURTH_MODEL_KEY);
                    int newTime = time * 60 * 1000;
                    if(domain.getProcessTime() >= newTime){
                        domain.setStatus(Constant.PROVIDER_ORDER_STATUS_fail);
                        domain.setRemark("订单不存在，请人工核实");
                    } else if(domain.getProcessTime() < newTime){
                        domain.setStatus(null);
                        domain.setRemark("订单不存在，请" + time + "分钟后重试");
                    }
//                    if(resultDomain.getModel(ResultDO.THIRD_MODEL_KEY) != null){
//                        domain.setStatus(Constant.PROVIDER_ORDER_STATUS_4);
//                        domain.setRemark((String) resultDomain.getModel(ResultDO.THIRD_MODEL_KEY));
//                    }
                }
            } else {
                domain.setStatus(null);
                domain.setRemark((String) resultDomain.getModel(ResultDO.THIRD_MODEL_KEY));
            }
        } else {
            domain.setStatus(null);
            domain.setRemark("供货商不存在");
        }
        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);
        return result;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO edit(ProviderOrderDO param, String userName) {
        ResultDO result = new ResultSupport();
        if(StringUtils.isEmpty(param.getId())
                || StringUtils.isEmpty(param.getOrderId())
                || param.getStatus() == null
                || (param.getStatus() != null && param.getStatus() == Constant.PROVIDER_ORDER_STATUS_2 && StringUtils.isEmpty(param.getVoucherNo()))
                || (param.getStatus() != null && param.getStatus() != Constant.PROVIDER_ORDER_STATUS_2 && param.getStatus() != Constant.PROVIDER_ORDER_STATUS_fail)
        ){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.PARAM_GET_ERROR);
            logger.info("error code：" + ErrorCode.PARAM_GET_ERROR.getCode() + " msg" + ErrorCode.PARAM_GET_ERROR.getMsg());
            return result;
        }
        result = this.get(param.getId());
        if(!result.isSuccess()){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ORDER_GET_PROVIDER);
            logger.info("error code：" + ErrorCode.ORDER_GET_PROVIDER.getCode() + " msg" + ErrorCode.ORDER_GET_PROVIDER.getMsg());
            return result;
        }
        ProviderOrderDO domain = (ProviderOrderDO) result.getModel(ResultDO.FIRST_MODEL_KEY);

        if(domain.getStatus() != Constant.PROVIDER_ORDER_STATUS_3 && domain.getStatus() != Constant.PROVIDER_ORDER_STATUS_4){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ORDER_EDIT_PROVIDER);
            logger.info("error code：" + ErrorCode.ORDER_EDIT_PROVIDER.getCode() + " msg" + ErrorCode.ORDER_EDIT_PROVIDER.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        String[] providerOrderIds = {param.getId()};
        Map<String, String> map = new HashMap<>();
        map.put(param.getOrderId() + "remark", param.getRemark());
        if(param.getStatus() == Constant.PROVIDER_ORDER_STATUS_2){
            map.put(param.getOrderId(), param.getVoucherNo());
        }

        result = this.updateBatch("", param.getStatus(), providerOrderIds, Constant.PROVIDER_ORDER_IS_OVER_1, map, userName);

        if(!result.isSuccess()){
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ORDER_SYNC_FAILED_ERROR);
            logger.info("error code：" + ErrorCode.ORDER_SYNC_FAILED_ERROR.getCode() + " msg" + ErrorCode.ORDER_SYNC_FAILED_ERROR.getMsg());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return result;
        }
        return result;
    }

    private ProviderOrderDO getDomain(ProviderOrderEntity entity) {

        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if(entity == null) return null;
        ProviderOrderDO domain = new ProviderOrderDO();

        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }

    private List<ProviderOrderDO> getDomainList(List<ProviderOrderEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<ProviderOrderDO> doList = new ArrayList<>();

        //判断传入的list的集合的size是否大于0
        if(list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for(ProviderOrderEntity entity : list) {

                ProviderOrderDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if(domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }
}
